const express = require('express');
const path = require('path');
const app = express();
const bodyParser = require('body-parser');
const session = require('express-session');
const config = require('config');
app.use(bodyParser.urlencoded({
    extended: false
}));
app.use(session({
    secret: 'secret key',
    saveUninitialized: false,
    cookie: {
        maxAge: 24 * 60 * 60 * 1000
    }
}));
const home = require('./router/home');
const admin = require('./router/admin');
const {
    nextTick
} = require('process');
require('morgan');
require('./model/connect');

const dateformat = require('dateformat');
// 在模板引擎中使用dateformat所需要的插件
const template = require('art-template');
const morgan = require('morgan');
template.defaults.imports.dateformat = dateformat;

app.engine('art', require('express-art-template'));
app.set('views', path.join(__dirname, 'views'));
app.set('view engine', 'art');
app.use(express.static(path.join(__dirname, 'public')));

app.use('/admin', require('./middleware/loginGuard.js'));

console.log(config.get('title'));
// 如何区分开发环境与生产环境
if (process.env.NODE_ENV == 'development') {
    console.log('当前是开发环境');
    // 在开发环境中，将客户端发送到服务器端的请求信息打印到控制台中
    app.use(morgan('dev'));
} else {
    console.log('当前是生产环境');
}

app.use('/home', home);
app.use('/admin', admin);

app.use((err, req, res, next) => {
    const result = JSON.parse(err);
    let params = [];
    for (let attr in result) {
        if (attr != 'path') {
            params.push(attr + '=' + result[attr]);
        }
    }
    res.redirect(result.path + '?' + params.join('&'));
})

app.listen(3001);
console.log('服务器启动成功，请访问localhost');